<?php

class Db {

	public $dbh;

	public function __construct() {
		$this->dbh = new PDO(DB_ENGINE . ':host=' . DB_HOST . '; dbname=' . DB_NAME . ';charset=UTF-8', DB_USER, DB_PASSWORD);
	}

	public function fetchAll($sql) {
		$stmt = $this->dbh->query($sql);

		$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
		$output = array();
		foreach ($result as $key => $val) {
			$output[$key] = $val;
		}
		return $output;
	}

	public function fetchRow($sql) {
		$stmt = $this->dbh->query($sql);

		$result = $stmt->fetch(PDO::FETCH_ASSOC);

		if ($result) {
			$output = array();
			foreach ($result as $key => $val) {
				$output[$key] = $val;
			}
		}else
			$output = false;

		return $output;
	}

	/**
	 * Dokonuje insertu
	 */
	public function DoINsert($sql){
		$this->dbh = new PDO(DB_ENGINE . ':host=' . DB_HOST . '; dbname=' . DB_NAME . ';charset=UTF-8', DB_USER, DB_PASSWORD);
		$this->dbh->exec($sql);
	}

	/**
	 * Zabezpiecza podany ciag znakow
	 *
	 * @param str $str
	 * @return str
	 */
	public function SecureUserInput($str) {
		$str = Db::RemoveSQLsyntax($str);
		$str = Db::StripTags($str);
		$str = Db::AddEscapeChars($str);

		return $str;
	}

	/**
	 * Usuwa slowa kluczowe skladni SQL
	 *
	 * @param str $str
	 * @return str
	 */
	public function RemoveSQLsyntax($str) {
		$forbiden_syntax = array("UNION",
			"SELECT",
			"UPDATE tbl_",
			"DELETE FROM",
			"ALTER TABLE",
			"javascript",
			"eval.",
			"document.write",
			"stringFromCharCode",
			"vbscript",
			"<script",
			"<script>",
			"alert",
			"</script>");
		$str = str_ireplace($forbiden_syntax, '', $str);

		return $str;
	}

	/**
	 * Usuwa tagi html z podanego ciagu znakow
	 *
	 * @param str $str
	 * @return str
	 */
	public function StripTags($str) {
		return strip_tags($str);
	}

	/**
	 * Dodaje znaki ucieczki do podanego ciagu znakow
	 *
	 * @param str $str
	 * @return str
	 */
	public function AddEscapeChars($str, $skip_secure = true, $remove_ms_office_tags = true) {
//		if ($remove_ms_office_tags)
//			$str = $this->RemoveMSOfficeTags($str);
		$str = Db::RemoveSQLsyntax($str);

		if (PARTNER > 0 && !$skip_secure) {
			$str = strip_tags($str, '<p><a><span><i><u><strong><strike><br><br /><br/><hr>');
		}

		return mysql_escape_string($str);
	}

}

?>